package com.qf.smsplatform.strategy.strategy.impl;

import com.qf.smsplatform.common.constants.RabbitMQConstants;
import com.qf.smsplatform.common.constants.StragetyConstents;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.strategy.Strategy;
import com.qf.smsplatform.strategy.util.PushErrorMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * projectName: sms-platform
 *
 * @author: 黄睿武
 * time: 2021/8/13 19:40
 * description:
 */


/**
 * 路由策略
 */
@Service(value = "router")
@Slf4j
public class RouterStrategyImpl implements Strategy {

    @Autowired
    private AmqpAdmin amqpAdmin;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 所有策略模块必须有的一个方法,用于校验或补全短信内容(submit对象)
     *
     * @param submit 短信内容
     * @return true代表通过, false校验未通过
     */
    @Override
    public boolean execute(StandardSubmit submit) {
        log.info("[策略模块-路由策略]  开始执行.......");
        String queueName = null;
        try {
            //将submit再次作为消息发送到指定的队列中
            //1.声明需要将当前消息发送到哪个队列
            queueName = RabbitMQConstants.TOPIC_SMS_GATEWAY + submit.getGatewayID();
            //2.创建队列,也可以手动的在图形化界面创建
            amqpAdmin.declareQueue(QueueBuilder.durable(queueName).build());
            //3.发送消息到待发Topic
            rabbitTemplate.convertAndSend(queueName,submit);
        } catch (AmqpException e) {
            PushErrorMessageUtil.sendLog(submit, StragetyConstents.STRATEGY_ERROR_ROUTER);
            PushErrorMessageUtil.sendReport(submit, StragetyConstents.STRATEGY_ERROR_ROUTER);
            log.error("[策略模块-路由策略]  发送消息到待发TOPIC失败 queName = {},ex = {}.......",queueName,e.getMessage());
            return false;
        }
        log.info("[策略模块-路由策略]  执行成功.......");
        return true;
    }
}
